import '../config/code.dart';

class NetRes<T> {
  final String? msg;
  late final T? data;
  late final List<T>? list;
  final NetResponseCode code;
  final dynamic dataJson;

  bool get isSuccess => code == NetResponseCode.success;

  NetRes({
    required this.code,
    this.msg,
    this.dataJson,
    T Function(Map<String, dynamic>)? fromJson,
  }) {
    if (fromJson != null) {
      _convert(fromJson);
    }
  }

  void _convert(T Function(Map<String, dynamic>) fromJson) {
    if (dataJson == null) return;
    if (dataJson is Map<String, dynamic>) {
      data = fromJson(dataJson);
    }
    if (dataJson is List) {
      list = (dataJson as List).map((e) => fromJson(e)).toList();
    }
  }

  factory NetRes.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>)? fromJson,
  ) {
    final code = int.tryParse(json['code'].toString()) ?? 999;
    final status = int.tryParse(json['status'].toString()) ?? 999;
    final data = json["data"];

    return NetRes(
      dataJson: data,
      code: NetResponseCode.getCode(code, status),
      msg: json['msg'] ?? json['message'],
      fromJson: fromJson,
    );
  }
}
